from flask import Flask, request, redirect, url_for, render_template_string
import sqlite3

app = Flask(__name__)

# 自动创建SQLite数据库（无需安装）
def init_db():
    conn = sqlite3.connect('users.db')
    c = conn.cursor()
    c.execute('''CREATE TABLE IF NOT EXISTS users
                 (username TEXT PRIMARY KEY, password TEXT)''')
    conn.commit()
    conn.close()

# 极简HTML界面（直接写在代码里，不用单独文件）
HTML = '''
<!doctype html>
<html>
<head><title>简易登录系统</title></head>
<body>
    <h2>{{ action }}</h2>
    <form method="POST">
        用户名: <input type="text" name="username"><br>
        密码: <input type="password" name="password"><br>
        <button type="submit">{{ button }}</button>
    </form>
    {% if message %}<p style="color:red">{{ message }}</p>{% endif %}
    <p><a href="{{ switch_url }}">{{ switch_text }}</a></p>
</body>
</html>
'''

@app.route('/', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        
        conn = sqlite3.connect('users.db')
        c = conn.cursor()
        c.execute("SELECT * FROM users WHERE username=?", (username,))
        user = c.fetchone()
        
        if user and user[1] == password:  # 实际项目要用密码加密！
            return f"欢迎回来, {username}！"
        return render_template_string(HTML,
            action="登录",
            button="登录",
            message="用户名或密码错误",
            switch_url=url_for('register'),
            switch_text="没有账号？去注册"
        )
    
    return render_template_string(HTML,
        action="登录",
        button="登录",
        message=None,
        switch_url=url_for('register'),
        switch_text="没有账号？去注册"
    )

@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        
        conn = sqlite3.connect('users.db')
        c = conn.cursor()
        try:
            c.execute("INSERT INTO users VALUES (?, ?)", (username, password))
            conn.commit()
            return redirect(url_for('login'))
        except sqlite3.IntegrityError:
            return render_template_string(HTML,
                action="注册",
                button="注册",
                message="用户名已存在",
                switch_url=url_for('login'),
                switch_text="已有账号？去登录"
            )
    
    return render_template_string(HTML,
        action="注册",
        button="注册",
        message=None,
        switch_url=url_for('login'),
        switch_text="已有账号？去登录"
    )

if __name__ == '__main__':
    init_db()  # 初始化数据库
    app.run(debug=True, port=5000)  # 访问 http://localhost:5000